
package com.ziq.zcamp.post

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.content.ContextCompat
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter
import com.donkingliang.groupedadapter.holder.BaseViewHolder
import com.ziq.base.base.BaseDialog
import com.ziq.zcamp.databinding.DialogCampDaySelectorBinding
import com.ziq.zcamp.util.TimeUtil
import com.ziq.zcamp.view.StatusView
import com.ziq.zcamp.view.layoutmanager.CalendarGridLayoutManager
import kotlinx.coroutines.*
import java.util.*
import com.ziq.base.extension.*
import com.ziq.zcamp.R
import com.ziq.zcamp.databinding.ItemCalendarCampDateBinding
import com.ziq.zcamp.databinding.ItemCalendarMonthHeaderBinding

class CampDaySelectorDialog(context: Context, val hasDefaultDate: Boolean = false, val lastStartDate:Date? = null, val lastEndDate:Date? = null) : BaseDialog(context) {

    companion object {
        const val TAG = "CampDaySelectorDialog"
    }

    private val binding: DialogCampDaySelectorBinding by binding()

    var adapter : MonthAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.decorView?.let {
            window?.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        }
        binding.root
        binding.btnClose.click {
            dismiss()
        }
        binding.btnNext.click {
            onNextCallback?.invoke(adapter?.startDateItem?.date, adapter?.endDateItem?.date)
            dismiss()
        }

        adapter = MonthAdapter(context)
        binding.rvMonth.adapter = adapter
        val calendarGridLayoutManager = CalendarGridLayoutManager(context, 7, adapter)
        binding.rvMonth.layoutManager = calendarGridLayoutManager

        adapter?.onSelectedCallback = { start, end ->
        }

        setAnimateView(binding.root)


        initData()
    }

    var onNextCallback : ((start: Date?, end: Date?) -> Unit)? = null
    fun setOnNextListener(callback: ((start: Date?, end: Date?) -> Unit)?) : CampDaySelectorDialog{
        this.onNextCallback = callback
        return this
    }

    val scope = CoroutineScope(Job() + Dispatchers.Main)
    fun initData(){
            scope.launch {
                var groupList: MutableList<MonthData> = mutableListOf()
                binding.statusView.setStatus(StatusView.LOADING)
                var totalCount = 0
                var startDateItem : DateItem? = null
                var endDateItem : DateItem? = null
                withContext(Dispatchers.Default){
                    val today = TimeUtil.getTodayWithoutTime()
                    var startDate = today.time
                    var endDate = today.time
                    try {
                        //可选的最早日期为2010/01/01
                        startDate = TimeUtil.yyyy_MM_dd_time_ss_DATE_FORMATTER.parse("2010-01-01 00:00:00")?:today.time
                    }catch (e:Exception){}

                    if(startDate.after(today.time)){
                        startDate = today.time
                    }

                    val endCalendar = TimeUtil.calendar(endDate)
                    val monthCount = TimeUtil.months(startDate, endCalendar.time)
                    val currentMonth = TimeUtil.calendar(startDate)
                    groupList.clear()
                    var monthData :MonthData? = null
                    for (i in 0..monthCount){
                        if(i != 0){
                            currentMonth.add(Calendar.MONTH, 1)
                        }
                        monthData = MonthData()
                        monthData.label = TimeUtil.yyyy_MM_DATE_FORMATTER_CN.format(currentMonth.time)
                        val position = TimeUtil.firstDayOfMonthIndex(currentMonth.time)
                        val dateCount = TimeUtil.maxDaysOfMonth(currentMonth.time)
                        //每个月第一天开始前的补全，当前行补全
                        if(position > 0){
                            for (index in 0 until position){
                                monthData.dateList.add(DateItem(true))
                            }
                        }

                        for (index in 1..dateCount){
                            currentMonth.set(Calendar.DAY_OF_MONTH, index)
                            val dateItem = DateItem()
                            dateItem.date = currentMonth.time
                            dateItem.isValidDate = startDate.time <= dateItem.date!!.time && dateItem.date!!.time <= endDate.time
                            monthData.dateList.add(dateItem)
                            if(lastStartDate == null && hasDefaultDate && dateItem.date?.time == today.time.time){
                                startDateItem = dateItem
                            }
                            if(lastStartDate != null && dateItem.date?.time == lastStartDate.time){
                                startDateItem = dateItem
                            }
                            if(lastEndDate != null && dateItem.date?.time == lastEndDate.time){
                                endDateItem = dateItem
                            }
                        }
                        if(i != monthCount && startDateItem == null){
                            totalCount += monthData.dateList.size + 2
                        }
                        groupList.add(monthData)
                    }
                }
                adapter?.setData(groupList, startDateItem, endDateItem)
                binding.rvMonth.post {
                    binding.rvMonth.scrollToPosition(totalCount)
                    (binding.rvMonth.layoutManager as CalendarGridLayoutManager).scrollToPositionWithOffset(totalCount, 0)
                    binding.statusView.setStatus(StatusView.IDLE)
                }
            }
    }

    override fun dismiss() {
        scope.cancel()
        super.dismiss()
    }

    override fun initWidth(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun initGravity(): Int {
        return Gravity.BOTTOM or Gravity.CENTER
    }

    class MonthAdapter(context: Context) : GroupedRecyclerViewAdapter(context){
        var groupList: MutableList<MonthData> = mutableListOf()
        var startDateItem: DateItem? = null
        var endDateItem: DateItem? = null

        var onSelectedCallback : ((start: DateItem?, end: DateItem?) -> Unit)? = null

        fun setData(groupList: MutableList<MonthData>, startDateItem: DateItem?, endDateItem: DateItem?) {
            this.groupList = groupList
            this.startDateItem = startDateItem
            this.endDateItem = endDateItem
            notifyDataChanged()
        }

        override fun getGroupCount(): Int {
            return groupList.size
        }

        override fun getChildrenCount(groupPosition: Int): Int {
            return groupList[groupPosition].dateList.size
        }

        override fun hasHeader(groupPosition: Int): Boolean {
            return true
        }

        override fun hasFooter(groupPosition: Int): Boolean {
            return true
        }


        override fun getHeaderLayout(viewType: Int): Int {
            return R.layout.item_calendar_month_header
        }

        override fun getChildLayout(viewType: Int): Int {
            return R.layout.item_calendar_camp_date
        }

        override fun getFooterLayout(viewType: Int): Int {
            return R.layout.item_calendar_month_footer
        }

        override fun onBindHeaderViewHolder(holder: com.donkingliang.groupedadapter.holder.BaseViewHolder?, groupPosition: Int) {
            holder?.let {
                val item = groupList[groupPosition]
                val binding = ItemCalendarMonthHeaderBinding.bind(holder.itemView)
                binding.tvMonth.text = "${item.label}"

//                if(groupPosition == 0){
//                    val lp = binding.root.layoutParams as GridLayoutManager.LayoutParams
//                    lp.topMargin = 0
//                    binding.root.layoutParams = lp
//                }else {
//                    val lp = binding.root.layoutParams as GridLayoutManager.LayoutParams
//                    lp.topMargin = GlobalContextCamp.getResources().getDimensionPixelSize(R.dimen.dimens_dip_24)
//                    binding.root.layoutParams = lp
//                }
            }
        }

        override fun onBindFooterViewHolder(holder: BaseViewHolder?, groupPosition: Int) {
        }

        override fun onBindChildViewHolder(
            holder: com.donkingliang.groupedadapter.holder.BaseViewHolder?,
            groupPosition: Int,
            childPosition: Int
        ) {
            holder?.let {
                val item = groupList[groupPosition].dateList[childPosition]
                val binding = ItemCalendarCampDateBinding.bind(holder.itemView)
                if(item.isEmpty || !item.isValidDate){
                    binding.root.click {}
                    binding.root.isSelected = false
                    binding.root.isEnabled = true
                    binding.tvDate.isEnabled = false
                    binding.tvDate.text = ""
                    if(item.date != null){
                        binding.tvDate.text = "${TimeUtil.calendar(item.date!!).get(Calendar.DAY_OF_MONTH)}"
                    }
                } else {
                    binding.root.click {
                        if(startDateItem == null || (startDateItem != null && endDateItem != null)){
                            //未选或已选择区间， 从头开始
                            startDateItem = item
                            endDateItem = null
                        } else {
                            //选了一个，进行第二个选择
                            if(startDateItem == item){
                                startDateItem = null
                                endDateItem = null
                            } else if(startDateItem?.date != null && item.date != null && item.date?.before(startDateItem?.date) == true){
                                startDateItem = item
                                endDateItem = null
                            } else if(startDateItem?.date != null && item.date != null && item.date?.after(startDateItem?.date) == true){
                                endDateItem = item
                            }
                        }
                        onSelectedCallback?.invoke(startDateItem, endDateItem)
                        notifyDataChanged()
                    }

                    binding.tvStatus.visibility = View.GONE
                    binding.tvDate.setTextColor(ContextCompat.getColorStateList(binding.tvDate.context, R.color.selector_calendar_date))
                    if(item.date != null){
                        if(item == startDateItem){
                            if(endDateItem != null){
                                binding.root.setBackgroundResource(R.drawable.selector_calendar_camp_date_start)
                                binding.tvStatus.visibility = View.VISIBLE
                                binding.tvStatus.text = "开始"
                            } else {
                                binding.root.setBackgroundResource(R.drawable.selector_calendar_date)
                            }
                            binding.root.isSelected = true
                        } else if(item == endDateItem){
                            binding.tvStatus.visibility = View.VISIBLE
                            binding.tvStatus.text = "结束"
                            binding.root.setBackgroundResource(R.drawable.selector_calendar_camp_date_end)
                            binding.root.isSelected = true
                        } else if(startDateItem?.date != null && endDateItem?.date != null && (item.date?.after(startDateItem?.date) == true && item.date?.before(endDateItem?.date) == true)){
                            binding.root.setBackgroundResource(R.drawable.selector_calendar_camp_date_center)
                            binding.tvDate.setTextColor(Color.parseColor("#AF8B6C"))
                            binding.root.isSelected = true
                        } else {
                            binding.root.setBackgroundResource(R.drawable.selector_calendar_date)
                            binding.root.isSelected = false
                        }
                    } else {
                        binding.root.setBackgroundResource(R.drawable.selector_calendar_date)
                        binding.root.isSelected = false
                    }

                    if(item.date != null){
                        binding.tvDate.text = "${TimeUtil.calendar(item.date!!).get(Calendar.DAY_OF_MONTH)}"
                    }
                    binding.root.isEnabled = true
                    binding.tvDate.isEnabled = true
                }

            }

        }

    }

    class MonthData {
        var label:String? = null
        var dateList:MutableList<DateItem> = mutableListOf()
    }

    class DateItem(empty :Boolean = false){
        var isEmpty = empty//补全第一天前的空格
        var date:Date? = null
        var isValidDate:Boolean = true
    }



}